<template>
  <el-dialog
    :title="type == 'add' ? '添加' : '修改'"
    v-model="visible"
    width="400px"
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="formRef"
      label-width="100px"
      class="good-form"
    >
      <el-form-item label="名称" prop="name">
        <el-input type="text" v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="图片" prop="url">
        <el-upload
          class="avatar-uploader"
          action="https://www.watabe-wedding.com.cn/mini/api/upload/img"
          accept="jpg,jpeg,png"
          :headers="{
            authorization: token,
          }"
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
          :on-success="handleUrlSuccess"
        >
          <img
            style="width: 100px; height: 100px; border: 1px solid #e9e9e9"
            v-if="ruleForm.url"
            :src="ruleForm.url"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="上级分类" prop="parentId">
        <el-select
          clearable
          placeholder="上级分类"
          v-model="ruleForm.parentId"
          size="small"
          style="width: 200px; margin-right: 10px"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="层级" prop="level" hidden>
        <el-input type="text" v-model="ruleForm.level"></el-input>
      </el-form-item>
      <el-form-item label="排序值" prop="order">
        <el-input-number
          size="medium"
          v-model="ruleForm.order"
          :min="1"
          :max="999"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { reactive, ref, toRefs, nextTick } from "vue";
import axios from "axios";
// import { localGet, uploadImgServer, hasEmoji } from '@/utils'
import { ElMessage } from "element-plus";

export default {
  name: "DialogAddWorksType",
  props: {
    type: String,
    reload: Function,
    options: Object,
  },
  setup(props) {
    const formRef = ref();
    const state = reactive({
      // uploadImgServer,
      token: localStorage.access_token,
      visible: false,
      ruleForm: {
        name: "",
        url: "",
        parentId: "",
        level: 2,
        order: 1,
      },
      rules: {
        name: [{ required: "true", message: "不能为空", trigger: ["change"] }],
        parentId: [{ required: "true", message: "不能为空", trigger: ["change"] }],
        url: [{ required: "true", message: "不能为空", trigger: ["change"] }],
        order: [{ required: "true", message: "不能为空", trigger: ["change"] }],
      },
      id: "",
    });
    // 上传图片
    const handleUrlSuccess = (val) => {
      console.log("handleUrlSuccess", val);
      state.ruleForm.url = val || "";
    };
    const handleBeforeUpload = (file) => {
      const sufix = file.name.split(".")[1] || "";
      if (!["jpg", "jpeg", "png"].includes(sufix)) {
        ElMessage.error("请上传 jpg、jpeg、png 格式的图片");
        return false;
      }
    };
    // 获取详情
    const getDetail = (id) => {
      axios.get(`/api/serverCategory/${id}`).then((res) => {
        console.log(res);
        state.ruleForm = {
          ...res.data,
        };
      });
    };
    // 开启弹窗
    const open = (id) => {
      state.visible = true;
      if (id) {
        state.id = id;
        getDetail(id);
      }
    };
    // 关闭弹窗
    const close = () => {
      state.visible = false;
    };
    const submitForm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          // if (hasEmoji(state.ruleForm.link)) {
          //   ElMessage.error('不要输入表情包，再输入就打死你个龟孙儿~')
          //   return
          // }
          if (state.ruleForm.token_expires) {
            state.ruleForm.token_expires = Number(state.ruleForm.token_expires);
          }
          if (props.type == "add") {
            axios({
              method: "post",
              url: "/api/serverCategory",
              data: {
                ...state.ruleForm,
              },
            }).then((res) => {
              console.log(res);
              ElMessage.success("添加成功");
              state.visible = false;
              if (props.reload) props.reload();
            });
          } else {
            axios
              .put("/api/serverCategory", {
                ...state.ruleForm,
              })
              .then(() => {
                ElMessage.success("修改成功");
                state.visible = false;
                if (props.reload) props.reload();
              });
          }
        }
      });
    };
    const resetForm = () => {
      nextTick(() => {
        formRef.value.resetFields();
      });
    };
    return {
      ...toRefs(state),
      open,
      close,
      formRef,
      submitForm,
      resetForm,
      handleBeforeUpload,
      handleUrlSuccess,
    };
  },
};
</script>

<style scoped>
.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}
.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
}
</style>